package net.entelijan.cobean.data.naming;

import java.util.Properties;

import javax.naming.NamingException;

import net.entelijan.cobean.data.naming.INamingClient;

import org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean;

public abstract class AbstractNamingClient implements INamingClient {

	public AbstractNamingClient() {
		super();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T lookup(String jndiName, Class<T> businessInterface) {
		try {
			SimpleRemoteStatelessSessionProxyFactoryBean sFactory = new SimpleRemoteStatelessSessionProxyFactoryBean();
			sFactory.setBusinessInterface(businessInterface);
			Properties props = createJndiProperties();
			if (props != null) {
				sFactory.setJndiEnvironment(props);
			}
			sFactory.setJndiName(jndiName);
			sFactory.afterPropertiesSet();
			return (T) sFactory.getObject();
		} catch (NamingException e) {
			throw new IllegalStateException("Naming client '" + getName()
					+ "' could not lookup '" + jndiName
					+ "' for businessInterface '" + businessInterface
					+ "' because: " + e.getMessage(), e);
		}
	}

	protected abstract String getName();

	protected abstract Properties createJndiProperties();

}
